import React from 'react';
import { Icon } from 'antd';
import { InputItem } from 'antd-mobile';
import cn from 'classnames';
import styles from './index.less';
import eye from '../../../images/eye.png';
import eyeInvisible from '../../../images/eye-invisible.png';

const Password = React.forwardRef(
    ({ label, placeholder = '请输入密码', value, clear, error, errorText, onChange, ...rest }, ref) => {
        const [open, setOpen] = React.useState(false);
        const [isActive, setIsActive] = React.useState(!!value);
        const [isFocus, setIsFocus] = React.useState(false);

        React.useEffect(() => {
            setIsActive(!!value);
        }, [value]);

        return (
            <div className={styles.passwordWrap}>
                {label && (
                    <div className={styles.label}>
                        <span className={cn({ [styles.active]: isFocus || isActive })}>{label}</span>
                    </div>
                )}
                <div className={styles.password}>
                    <InputItem
                        ref={ref}
                        value={value}
                        onChange={onChange}
                        {...rest}
                        type={open ? 'text' : 'password'}
                        placeholder={label ? '' : placeholder}
                        onFocus={() => setIsFocus(true)}
                        onBlur={() => setIsFocus(false)}
                        clear={false}
                    ></InputItem>
                    {error && (
                        <div className={styles.iconBtn}>
                            <Icon type="info-circle" theme="filled" style={{ fontSize: 16, color: '#F55656' }} />
                        </div>
                    )}
                    {clear && value && (
                        <div
                            className={styles.iconBtn}
                            onClick={() => {
                                if (onChange) onChange(undefined);
                            }}
                        >
                            <Icon type="close-circle" theme="filled" style={{ fontSize: 16, color: '#858B9B' }} />
                        </div>
                    )}
                    <div className={styles.iconBtn} onClick={() => setOpen(!open)}>
                        <img alt="" src={open ? eye : eyeInvisible} width="16" height="16" />
                    </div>
                </div>
                {error && errorText && <div className={styles.error}>{errorText}</div>}
            </div>
        );
    }
);

export default Password;
